Skip to content

fix(daemon): defer artifact cleanup until active downloads close - #4165

Merged
thymikee merged 12 commits into
mainfrom
fix/artifact-directory-download-race
Nov 2, 2026
Merged

thymikee merged 12 commits into
mainfrom
fix/artifact-directory-download-race

Conversation

@thymikee

@thymikee thymikee commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Keep directory archives and sources owned until downloads settle, with abortable pipelines, bounded lifetimes, teardown, immediate ID retirement, and JSON open errors. Cancel shared archive preparation only after every active download is cancelled.

FU-ART; seven files; artifact-download scope. Prior blocker: #4060 (not reproduced).

Validation

  • Base: a0e7c7dc239922bf93adaceff20a2f7e78579146; prior reviewed head: 3a4f1582ae989b722b3c428c90fa2a232b1a6ab1; tested head: e4ad2f37e3381dc09ad1b382e1ffe17e3599d5f1.
  • Red first: cancelling archive-builder A caused waiting B to fail with A’s RESOURCE_EXPIRED error; the same test now verifies B’s complete archive payload. All-waiter cancellation still aborts preparation and removes files; real HTTP client-abort coverage also passes.
  • Truncation and deadline-first tests preserve source data, prove registration expiry remains armed, and verify bounded source/archive cleanup; neither additional permanent-leak claim reproduced.
  • Explicit wire/HTTP/owner selection: 330 passed. pnpm format: passed.
  • Foreground pnpm check:affected --run --head e4ad2f37e3381dc09ad1b382e1ffe17e3599d5f1: passed; receipt run-SWZ47c, exactCommit=true, checkoutChanged=false; 16,988 unit passed, 304 related passed; all runnable stages passed.
  • Released-wire compatibility passed; protocol 2 unchanged.
  • Live private-state daemon: two identical 16,782,807-byte curl archives, each containing the full 16 MiB payload; preparation and streaming aborts at 0/167,936 bytes; source/inventory cleaned, daemon stopped.
  • Mutable-source growth remains deferred. New-head CI/native lanes pending; cold self-review only this round.

View guided diff Turn on auto-fix

@vercel

vercel Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
agent-device-website Ready Ready Preview Nov 2, 2026 12:42pm UTC

Request Review

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.69 MB 5.69 MB +2.0 kB
Package (unpacked) 5.69 MB 5.69 MB +2.0 kB
Package (download) 1.73 MB 1.73 MB +714 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 37.8 ms 38.6 ms +0.8 ms
CLI --help 77.7 ms 76.3 ms -1.4 ms

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread website/docs/docs/remote-proxy.md Resolved

@thymikee thymikee left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review: one P2 finding at head d7b2350866de48ec17dba50e50c45948b49e6b2d (merge-base a0e7c7dc239922bf93adaceff20a2f7e78579146).

  • P2 — Release the acquired stream when HTTP setup throws — packages/daemon/src/server/downloadable-artifact-http.ts:94-105 (catch at :133-134). openDownloadableArtifact now increments activeDownloads and returns an already-created stream, but setHeader runs before the stream error/response-close handlers are installed. A valid artifact filename such as trace-💥 passes safeArtifactFilename and makes Node reject the Content-Disposition header. The catch sends 500 without destroying the stream, which remains paused/open and never releases its reader count. Unlike base, expiry/disposal can now leave the source and generated archive permanently undeleted because cleanup always sees an active download. Reproduced through the real HTTP route: after the 500 and explicit cleanup, streamClosed=false, destroyed=false, sourceExists=true, archiveExists=true; manually destroying the abandoned stream immediately permits cleanup. Keep the acquired stream available to the catch and destroy it on every setup failure; install its error handling before operations that can throw. Add a regression covering cleanup after this failure.

Validation (no CI wait): installed/built each checkout, then ran the same affected selection once per checkout: pnpm exec vitest run --project unit-core packages/daemon/src/server/downloadable-artifact-http.test.ts packages/daemon/src/resources/artifact-tracking.test.ts packages/daemon/src/server/__tests__/http-server-artifacts.test.ts packages/daemon/src/server/http/daemon-runtime-artifacts.test.ts. Head: 14 passed. Base with only the new regression test copied into a disposable checkout: 12 passed, 2 failed, both at the intended archive-exists assertion (downloadable-artifact-http.test.ts:89).

Additional scratch probes passed for mid-read abort/error release, a real HTTP disconnect, blocked admission after cleanup/expiry, one shared in-flight archive build for overlapping downloads and inventory/download overlap, inventory filtering during cleanup, and last-reader deletion. Existing tests cover ordinary file artifacts and retained sources. The map identity guard prevents duplicate cleanup; the timer is cleared rather than rearmed while readers remain active. Design: the reader counter plus terminal cleanup-request flag is a small, sufficient state model; the remaining issue is exception-safe ownership transfer to HTTP.

Reviewed source stayed read-only. Logs: /tmp/r4165-head-tests.log, /tmp/r4165-base-tests.log, /tmp/r4165-probe.log.

@apex-sentinel-staging

apex-sentinel-staging Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Apex Sentinel

Verdict: approve

Since the last review: 6 new · 1 still open · 7 no longer raised

7 finding(s): 4 minor, 3 nit. Verdict: approve.

🟡 Minor (4)

Where Finding
packages/daemon/src/resources/artifact-tracking.ts:20 🆕 Two constants holding the same 15-minute value are kept in sync only by the error-message text
packages/daemon/src/resources/artifact-tracking.ts:196 🆕 openDownloadableArtifact creates the ReadStream inside the try, so a failed open is never awaited and the 500 path leaves the stream and its deadline running
packages/daemon/src/resources/artifact-tracking.ts:131 🆕 findArtifactSourceCleanup only scans live entries, so a re-registration after cleanup does not inherit the shared source's deleteAfterDownload=false and deletes a file another artifact still owns
packages/daemon/src/resources/artifact-tracking.ts:179 Download deadline fires mid-transfer and turns an in-progress artifact read into a failed response
🔵 Nit (3)
Where Finding
packages/daemon/src/resources/artifact-tracking.ts:184 🆕 release() returns early on the second call, skipping the deadline clear
packages/daemon/src/server/downloadable-artifact-http.ts:122 🆕 Mid-stream size validation breaks downloads of artifacts that grow after registration
packages/daemon/src/server/downloadable-artifact-http.ts:143 🆕 Error path clears content-length and content-disposition but not the artifact content-type

Reply under an inline comment with @apex-sentinel-staging note ... or @apex-sentinel-staging pivot ... to re-check that finding.
Comment @apex-sentinel-staging review on this conversation to run a full review.

Earlier reviews

Review of 3a4f1582 · 02.11.2026 12:31 UTC

Apex Sentinel

Verdict: approve

Since the last review: 6 new · 2 still open · 5 no longer raised

8 finding(s): 4 minor, 4 nit. Verdict: approve.

🟡 Minor (4)

Where Finding
packages/daemon/src/resources/artifact-tracking.ts:214 One download's cancellation aborts the archive tar another active download is waiting on
packages/daemon/src/resources/artifact-tracking.ts:188 🆕 An orphaned directory archive is never removed when the download's own deadline fires
packages/daemon/src/server/downloadable-artifact-http.ts:113 🆕 The HTTP byte threshold cleanup no longer honors retainArtifacts
packages/daemon/src/server/downloadable-artifact-http.ts:122 🆕 A truncated artifact read no longer retires the artifact: flush error returns before cleanup
🔵 Nit (4)
Where Finding
packages/daemon/src/resources/artifact-tracking.ts:20 🆕 Download deadline constant is duplicated with the cleanup timeout and only works because the two values are equal today
packages/daemon/src/resources/artifact-tracking.ts:110 🆕 New public API OpenedDownloadableArtifact has no doc on its two behavioural members
packages/daemon/src/resources/artifact-tracking.ts:131 Shared source-cleanup refcount is monotonically sticky: one caller opting out of deletion permanently disables deletion of the file for later registrations of the same path
packages/daemon/src/resources/artifact-tracking.ts:419 🆕 canReadArtifact now answers three different questions
Review of 89f63cbc · 02.11.2026 12:08 UTC

Apex Sentinel

Verdict: approve

Since the last review: 5 new · 2 still open · 5 no longer raised

7 finding(s): 5 minor, 2 nit. Verdict: approve.

🟡 Minor (5)

Where Finding
packages/daemon/src/resources/artifact-tracking.ts:131 Shared source-cleanup ownership silently drops the delete intent of the first registration
packages/daemon/src/resources/artifact-tracking.ts:198 🆕 cancelArtifactDownload aborts the shared entry.archiveAbortController when the canceled download has no stream yet, s…
packages/daemon/src/resources/artifact-tracking.ts:445 🆕 Shared source-cleanup counter is lost when every registration for a path is still deferred, leaking the source directory forever
packages/daemon/src/resources/artifact-tracking.ts:445 🆕 A stalled download can permanently orphan an artifact source file (and its archive temp dir)
packages/daemon/src/server/downloadable-artifact-http.ts:113 A mid-stream size overrun deletes the artifact before the declared length is validated, turning a truncated response into a lost artifact
🔵 Nit (2)
Where Finding
packages/daemon/src/resources/artifact-tracking.ts:21 🆕 Two 15-minute constants with one value, and one of them names the wrong thing
packages/daemon/src/resources/artifact-tracking.ts:376 🆕 Tar's spawn timeout reuses the download lifetime and is silently required to stay >= it
Review of f401c7d1 · 02.11.2026 11:38 UTC

Apex Sentinel

Verdict: approve

Since the last review: 4 new · 3 still open · 8 no longer raised

7 finding(s): 3 minor, 4 nit. Verdict: approve.

🟡 Minor (3)

Where Finding
packages/daemon/src/server/downloadable-artifact-http.test.ts:107 🆕 fireDeadlines in the new fixture fires the artifact expiry timer too, so the deadline case does not test what its name claims
packages/daemon/src/server/downloadable-artifact-http.ts:118 🆕 Truncated artifact read leaves the source and its temp archive undeleted until the 15-minute expiry
packages/daemon/src/resources/artifact-tracking.ts:131 Any pending download entry now blocks registering another tenant's artifact at the same path
🔵 Nit (4)
Where Finding
packages/daemon/src/resources/artifact-tracking.ts:76 Disposal correctness depends on an unstated call ordering between requestArtifactCleanup and cancelArtifactDownload
packages/daemon/src/resources/artifact-tracking.ts:445 A stalled or aborted download holds the whole artifact source on disk for a second 15 minutes
packages/daemon/src/server/downloadable-artifact-http.ts:109 🆕 Mid-stream cleanup now unlinks the source before the final chunk reaches the socket
packages/daemon/src/server/downloadable-artifact-http.ts:124 🆕 retainArtifacts skips a size check that is the pipeline's only failure signal
Review of 56cf7bb7 · time not recorded

Apex Sentinel

Verdict: request_changes

Since the last review: 6 new · 0 still open · 7 no longer raised

6 finding(s): 1 major, 2 minor, 3 nit. Verdict: request_changes. reached max rounds (1).

Required fixes

  • pipeArtifactDownload leaves the response unfinished when the file read fails or the stream ends early, unlike the piped predecessor

🟠 Major (1)

Where Finding
packages/daemon/src/server/downloadable-artifact-http.ts:142 🆕 pipeArtifactDownload leaves the response unfinished when the file read fails or the stream ends early, unlike the piped predecessor

🟡 Minor (2)

Where Finding
packages/daemon/src/resources/artifact-tracking.ts:125 🆕 Doomed entries stay in the registry, so trackDownloadableArtifact can hand back an id that 404s and whose file is then deleted
packages/daemon/src/resources/artifact-tracking.ts:370 🆕 Deferred cleanup drops the timer, so a hung download can leak the entry forever
🔵 Nit (3)
Where Finding
packages/daemon/src/resources/artifact-tracking.ts:57 🆕 New runtime-slot teardown path is never exercised and the new test never disposes its runtime, so the dispose-time leak stays hidden
packages/daemon/src/resources/artifact-tracking.ts:138 🆕 openDownloadableArtifact returns a widened type instead of its own name
packages/daemon/src/server/downloadable-artifact-http.ts:150 🆕 pipeArtifactDownload ignores stream.resume()'s return value and its own end path

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 7 new findings on d7b2350. The verdict and the full list are in the summary comment.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 6 new findings on 56cf7bb. The verdict and the full list are in the summary comment.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 7 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@thymikee

thymikee commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

f401c7d121cff19933aa22ca707c8918b2c08a80 pushed once for this revision round. Replaced the custom pipe with a bounded, abortable Node pipeline; fixed re-registration, active teardown, and retention docs.

321 explicit tests passed; the full exact-head affected gate passed (exactCommit=true, checkoutChanged=false). Live: two complete 16 MiB downloads plus one mid-download abort. Requested threads are replied to and resolved; new-head CI is pending.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 4 new findings on f401c7d. The verdict and the full list are in the summary comment.

@thymikee

thymikee commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Pushed 89f63cbca95dac8f6233825eec389bc4141acdcb once for this round. The pre-ready error regression failed first and now returns complete JSON; 322 explicit wire/HTTP/owner tests and the foreground exact-head gate passed (16,980 unit, 304 related; run-WQ2gA5, exact commit, unchanged checkout). Live: two complete concurrent archives plus one aborted download, followed by cleanup. Both Cubic threads and remaining Sentinel findings have replies and are resolved; tenant registration already has owner-scoped lookup. New-head CI is pending.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 3 new findings on 89f63cb. The verdict and the full list are in the summary comment.

@thymikee

thymikee commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Pushed test-only head 3a4f1582ae989b722b3c428c90fa2a232b1a6ab1 once. Neither permanent-leak scenario reproduces: both deferred registrations clean up after disposal in either close order, and the independent stalled-download deadline removes source/archive after pending I/O closes without runtime re-entry. All 325 explicit wire/HTTP/owner tests and the foreground exact-head gate passed (16,983 unit, 304 related; receipt run-UIKana). All threads have dispositions and are resolved; new-head CI remains pending.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 3 new findings on 3a4f158. The verdict and the full list are in the summary comment.

@thymikee

thymikee commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Pushed e4ad2f37e3381dc09ad1b382e1ffe17e3599d5f1 once. The archive-builder cancellation regression failed first and now preserves the other download; cancelling all waiters still stops tar and cleans up. Truncation/deadline tests found bounded expiry cleanup, with no source loss or permanent leak. All 330 explicit tests and the foreground exact-head gate passed (16,988 unit, 304 related; run-SWZ47c). Live curl: two complete matching archives plus preparation/stream aborts, followed by cleanup. Every thread has a reply and is resolved; new-head CI is pending.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on e4ad2f3. The verdict and the full list are in the summary comment.

@thymikee

thymikee commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

The code looks good at e4ad2f3. All 21 checks are green at that commit, and there are no conflicts.

Not blocking, and fine to take or leave: (1) a client that disconnects while a directory archive is still being prepared does not cancel the download, so a lone waiter leaves tar running until it ends or hits the 15-minute timeout (the rule: a download is cancelled when its HTTP client goes away, in every phase, e.g. by passing an AbortSignal into openDownloadableArtifact and aborting on response close); (2) after a deadline aborts the shared tar, a new download can join the aborted archive promise and get RESOURCE_EXPIRED for a live artifact (artifact-tracking.ts#L334); (3) the post-tar cleanupRequested && activeDownloads.size === 0 check cannot fire, since the abort on the line above already throws (artifact-tracking.ts#L395); (4) the catch in downloadable-artifact-http.ts#L144 repeats failStreamedHttpResponse, and the other streamed route now fails differently before headers; (5) the client-abort test would also pass on base, and it spies on a module export and finds timers by position, so waiting on an observable state would be sturdier.

I did not re-run the tests or check:affected, so I relied on green CI and code reading. I could not see a log of the live daemon run or the red-first result against 3a4f158, and I did not reproduce the race in (2).

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 2, 2026
@thymikee
thymikee merged commit e6324c1 into main Nov 2, 2026
21 checks passed
@thymikee
thymikee deleted the fix/artifact-directory-download-race branch November 2, 2026 13:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant